<template>
<label :class="{'is-invalid-label': errors.has(name)}">{{ label }}
  <field-error v-show="errors.has(name)" :err="errors.first(name)" />
  <select v-model="selectedVal" @change="valueChangeHandler" :name="name" v-validate="rules" :disabled="isReadonly">
    <option v-if="defaultOption" :value="defaultOption.val" :disabled="isRequired">{{ defaultOption.txt }}</option>
    <option v-for="(item, idx) in items" :key="idx" :value="item.val">{{ $t(item.txt) }}</option>
  </select>
</label>
</template>

<script>
import FieldError from './FieldError';

export default {

  components: {
    FieldError
  },

  inject: ['$validator'],

  data() {
    return {
      selectedVal: this.initVal
    };
  },

  computed: {
    rules() {
      return {
        required: this.isRequired
      };
    }
  },

  methods: {
    valueChangeHandler() {
      this.$emit('select', {
        key: this.name,
        val: this.selectedVal
      });
    },

    reset() {
      if (this.defaultOption) {
        this.selectedVal = this.defaultOption.val;
      } else {
        this.selectedVal = this.items[0].val;
      }
      this.$emit('select', {
        key: this.name,
        val: this.initVal
      });
    }
  },

  watch: {
    initVal() {
      this.selectedVal = this.initVal;
    }
  },

  props: {
    label: {
      type: String,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    items: {
      type: Array,
      default() {
        return [];
      }
    },
    defaultOption: {
      type: Object
    },
    isRequired: {
      type: Boolean
    },
    initVal: {
      type: [String, Number]
    },
    isReadonly: {
      type: Boolean
    }
  }
};
</script>
